// pages/recovery/recovery.js

import {
  startRecovertOta,
  zip2UpdateTask
} from '../../recovery_ota/recovery_ota.js'

import {
  CRC32
} from '../../ota/CRC32.js';

Page({


  data: {
    deviceId: null,
    otaTasks: [], //fileIndex,rawdata,crc32,name
  },
  onFindDeviceTap: function (e) {
    this.setData({
      currentIndex: 0
    })
    wx.navigateTo({
      url: '../scan/scan'
    })
  },
  onSelectFileTap: function (e) {
    this.setData({
      currentIndex: 1
    })
    var that = this
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['zip', 'ZIP'],
      success(res) {
        that.onFileSelected(res.tempFiles[0].path)
        console.log(res)
        //res.tempFiles[0].path
        //{name: "template_ota.bin",size: 49456,path: "wxfile://tmp_3dbeb0ceed5857ff824a0b8200633c98cc1744d536596693.bin",}
      }
    })
  },

  onFileSelected(tmpFilePath) {
    /**
     * name
     * fileIndex: Int
     * rawData: ArrayBuffer
     * crc32: Int
     */
    var that = this
    const fs = wx.getFileSystemManager()
    fs.readZipEntry({
      filePath: tmpFilePath,
      entries: 'all',
      success(res) {
        console.log(res)
        for (var fileName in res.entries) {
          console.log(fileName)
          var index = fileName.lastIndexOf(".");
          var ext = fileName.substr(index + 1);
          if (ext.toLowerCase() == 'json') {
            console.log(res.entries[fileName])

            var floderIndex = fileName.lastIndexOf("/");
            let floderPath = fileName.substr(0, floderIndex)
            if (floderPath.length > 0) {
              floderPath = floderPath + '/'
            }

            let obj = res.entries[fileName]
            that.parseJsonFile(obj.data, res.entries, floderPath)
            break
          }
        }
      },
      fail(e) {
        console.error(e)
      }
    })
  },
  /**
   * @param {String} jsonFileName //名字可能是这个 OTA/list.json
   */
  parseJsonFile(ab, entries, floderPath) {

    // 将其转换为uint8字节流
    var uint8_msg = new Uint8Array(ab);
    // 解码成字符串
    var decodedString = String.fromCharCode.apply(null, uint8_msg);
    console.log(decodedString);
    // parse,转成json数据
    var table = JSON.parse(decodedString);
    console.log(table);
    let otaTasks = []


    for (var index in table) {
      let fileName = table[index]

      let paramKey = floderPath + fileName // todo 动态替换
      let rawData = entries[paramKey].data
      console.log(fileName, rawData)

      let crc = new CRC32()
      let u8Array = new Uint8Array(rawData)
      let signedCrcValue = crc.crc32(u8Array, 0, rawData.byteLength) //有符号
      let unsignedCrc32Value = signedCrcValue >>> 0 //无符号

      let task = {
        fileIndex: index,
        name: fileName,
        rawData: rawData, //ab
        size: rawData.byteLength,
        crc32: unsignedCrc32Value
      }
      console.log(task)
      otaTasks.push(task)
    }

    this.setData({
      otaTasks: otaTasks
    })

  },
  onDeviceSelected(deviceId) {
    this.setData({
      deviceId: deviceId
    })
    this.applyCurrentIndex()
  },
  applyCurrentIndex() {
    var index = 0
    if (this.data.deviceId && this.data.otaTasks.length > 0) {
      index = 2
    } else if (this.data.deviceId && this.data.otaTasks.length == 0) {
      index = 0
    } else if (this.data.deviceId == null && this.data.otaTasks.length > 0) {
      index = 1
    } else {
      0
    }
    let that = this
    setTimeout(() => {
      that.setData({
        currentIndex: index
      })
    }, 100)
  },
  onStartTap(e) {
    let that = this
    this.setData({
      updating: true,
      currentIndex: 2
    })
    wx.setKeepScreenOn({
      keepScreenOn: true,
    })
    let onStateChanged = function (state) {

    }
    let onFinish = function (res) {

    }
    if (that.data.deviceId && that.data.otaTasks.length > 0) {
      startRecovertOta(that.data.deviceId, that.data.otaTasks)
    }

  },


})